<?php
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;

$exchange_name = 'router';
$queue_name = 'msgs';
$routing_key   = 'key';

include_once __DIR__.'/config.php';

$connectsion = new AMQPStreamConnection(HOST,PORT,USER,PASS,VHOST);

$channel = $connectsion->channel();

//开启监听模式
$channel->confirm_select();

//监听数据,成功
$channel->set_ack_handler(function (AMQPMessage $message){
    //update 订单表 set is_send_succ=ture
    echo "Message acked with content " . $message->body . PHP_EOL;
});

//监听数据,失败
$channel->set_nack_handler(function (AMQPMessage $message){
    //update 订单表 set is_send_succ=false
    echo "Message nacked with content " . $message->body . PHP_EOL;
});

//$args = new AMQPTable(['x-max-length' => 10]);

$args = new AMQPTable();

$args->set('x-max-length', 10, 1);

// 将第三个参数设置为true，表示将队列持久化
$channel->queue_declare($queue_name,false,true,false,false,false,$args);

// 将第四个参数设置为true，表示将交换机持久化
$channel->exchange_declare($exchange_name,AMQP_EX_TYPE_DIRECT,false,true,false);

$channel->queue_bind($queue_name,$exchange_name,$routing_key);

$i = 1;
while ($i <= 100){
    $content = '这是消息内容' . $i++;
    //实力消息类
    // 设置delivery_mode为DELIVERY_MODE_PERSISTENT，表示将消息持久化
    $msg = new AMQPMessage($content,['content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
    $channel->basic_publish($msg,$exchange_name,$routing_key);
}

//监听写入
$channel->wait_for_pending_acks();

$channel->close();
$connectsion->close();